package com.gitee.cashzhang.test.basic.base;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/04/24 15:37
 */
public class HashCodeEquals {
/*
1、如果两个对象equals，Java运行时环境会认为他们的hashcode一定相等。
2、如果两个对象不equals，他们的hashcode有可能相等。
3、如果两个对象hashcode相等，他们不一定equals。
4、如果两个对象hashcode不相等，他们一定不equals。
*/

  public static void main(String[] args) {
    HashCodeEquals hashCodeEquals = new HashCodeEquals();
    A a = new A();
    A b = new A();

    Map<A,Object> map = new HashMap<>();
    map.put(a,new Object());
    map.put(b,new Object());
    System.out.println(map.size());
    System.out.println(map.get(a));
    System.out.println(map.get(b));
    System.out.println("-----");
    Map<Integer,Integer> t = new HashMap<>(5);
    t.put(1,1);
    t.put(2,2);
    t.put(3,3);
    t.put(4,4);
    System.out.println("-----");
    Map<Integer,Integer> f = new HashMap<>();
    f.put(1,1);
    f.put(2,2);
    f.put(3,3);
    f.put(4,4);
    f.forEach((k, v) ->
        System.out.println(k + ":" + v)
    );
    System.out.println("-----");
    int one = 1;
    int two = 2;
    System.out.println(hashCodeEquals.hash(one));
    System.out.println(hashCodeEquals.hash(two));
    System.out.println("-----");
    String oneStr = "1";
    String twoStr = "2";
    Map j = new HashMap();
    j.put(oneStr,1);
    j.put(twoStr,1);
    j.forEach((k, v) ->
        System.out.println(k + ":" + v)
    );
    System.out.println("-----");
    System.out.println(hashCodeEquals.hash(oneStr));
    System.out.println(hashCodeEquals.hash(twoStr));
    System.out.println("-----");
    Map<String,Integer> g = new HashMap<>();
    g.put("one",1);
    g.put("two",2);
    g.put("three",3);
    g.put("four",4);
    g.put("five",5);
    g.forEach((k, v) ->
        System.out.println(k + ":" + v)
    );
  }

  int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  }
}

class A {

  @Override
  public int hashCode() {
    System.out.println("判断hashcode");
    return 1;
  }

  @Override
  public boolean equals(Object obj) {
    System.out.println("判断equals");
    return false;
  }
}